package com.cacho.s2b.lesson.learn;

import com.cacho.s2b.lesson.utils.DealCert;

import java.io.File;
import java.io.FileInputStream;
import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.cert.Certificate;
import java.util.Enumeration;

/**
 * @Description 获取pkcs12证书的 CERTIFICATE，公钥，私钥  P12文件通常使用PKCS#12标准进行编码
 * @Author LingWei
 * @date 2023/12/14
 **/

public class LearnP12 {
    public static void main(String[] args) throws Exception {
        String keystorePath = "C:\\Users\\1633449\\Downloads\\OpenBanking\\key\\scbapibanking.p12"; // 指定密钥库文件路径
        char[] password = "123456".toCharArray(); // 指定密钥库的密码
        KeyStore keyStore = KeyStore.getInstance("PKCS12");
        FileInputStream fis = new FileInputStream(new File(keystorePath));
        keyStore.load(fis, password);

        Enumeration<String> aliases = keyStore.aliases();
        while (aliases.hasMoreElements()) {
            String alias = aliases.nextElement();
            if (keyStore.isKeyEntry(alias)) {
                System.out.println("Alias: " + alias);
                // 1. 获取私钥
                 PrivateKey privateKey = (PrivateKey) keyStore.getKey(alias, password);
                 DealCert.saveCert("privateKey", LearnBase64.encode(privateKey.getEncoded()));

                Certificate cert = keyStore.getCertificate(alias);
                // 2. 获取公钥
                DealCert.saveCert("publicKey", LearnBase64.encode(cert.getPublicKey().getEncoded()));
                // 3. 获取 certificate
                String base64Cert = LearnBase64.encode(cert.getEncoded());
                DealCert.writeStringToFile(DealCert.saveCert("crt", base64Cert),"C:\\Users\\1633449\\goldenversions\\openssl-0.9.8\\bin\\psd.crt");
            }
        }

        fis.close();
    }
}
